package com.huwei.data.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.huwei.data.AuthenticationDataSource;
import com.huwei.data.manager.DataSourceManagerFacotry;
import com.huwei.data.manager.DataSourceOperation;
import com.huwei.entity.UserAccount;
import com.huwei.util.cryption.MD5Util;

/**
 * 内存测试
 * @author huwei
 */
@Order(1)
@Component("memoryDataSource")
public class AuthenticationMomeryDataSource implements AuthenticationDataSource{
	
	private Map<String ,UserAccount> userMap = new HashMap<String, UserAccount>();
	{
		//default and test
		UserAccount user = new UserAccount();
		user.setUsername("test");
		user.setPhone("18523102563");
		user.setPassword(MD5Util.encypt("test"));
		userMap.put(user.getUsername(), user);
	}

	@Override
	public UserAccount findByUsername(String username) {
		return userMap.get(username);
	}

	@Override
	public UserAccount findById(long id) {
		for(Map.Entry<String, UserAccount> entry : userMap.entrySet()) {
			UserAccount user = entry.getValue();
			if(id == user.getId()) {
				return user;
			}
		}
		return null;
	}

	@Override
	public UserAccount save(UserAccount user) {
		//不保存注册的用户，避免不能正确读取数据库中的数据；
		//userMap.put(user.getUsername(), user);
		
		DataSourceOperation dso = DataSourceManagerFacotry.getDataSourceUtil().next(AuthenticationDataSource.class, this.getClass());
		
		return  (UserAccount) dso.invokeCurrentMethod();
	}

	@Override
	public UserAccount findByPhone(String phone) {
		for(Map.Entry<String, UserAccount> entry : userMap.entrySet()) {
			UserAccount user = entry.getValue();
			if(phone.equals(user.getPhone())) {
				return user;
			}
		}
		return null;
	}

}
